<script>
import { page, updateStatus } from '@/api/userinfo';
import { FilterMatchMode } from '@primevue/core/api';
import Button from 'primevue/button';
import InputText from 'primevue/inputtext';
import { useToast } from 'primevue/usetoast';
import Dropdown from 'primevue/dropdown';
import TreeSelect from 'primevue/treeselect';
import { useRouter } from 'vue-router';
import { formatDateTime } from '@/utils/datetimeutil';
import Calendar from 'primevue/calendar';

export default {
    components: {
        Calendar,
        InputText,
        Button,
        Dropdown,
        TreeSelect
    },
    data() {
        return {
            users: [],
            user: {
                id: null,
                code: '',
                questionBankId: null,
                questionBankName: '',
                status: 1,
                role: 0,
                createTime: null,
                updateTime: null
            },
            statuses: [
                { label: '有效', value: 1 },
                { label: '无效', value: 0 }
            ],
            roles: [
                { label: '管理员', value: 1 },
                { label: '用户', value: 0 }
            ],
            selectedUser: null,
            deleteUserDialog: false,
            loading: false,
            filters: {
                global: { value: null, matchMode: FilterMatchMode.CONTAINS }
            },
            pageSize: 10,
            pageNum: 1,
            totalRecords: 0,
            searchQuery: {
                id: null,
                email: null,
                status: null,
                role: null,
                createTimeRange: null
            }
        };
    },
    mounted() {
        this.loadUser();
    },
    methods: {
        async loadUser() {
            this.loading = true;
            try {
                const params = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    ...this.searchQuery
                };

                if (this.searchQuery.createTimeRange) {
                    params.createTimeStart = formatDateTime(this.searchQuery.createTimeRange[0]);
                    params.createTimeEnd = formatDateTime(this.searchQuery.createTimeRange[1]);
                }
                delete params.createTimeRange;

                const response = await page(params);

                if (response.code === 200) {
                    this.users = response.data.list || [];
                    this.totalRecords = response.data.total || 0;
                } else {
                    this.$toast.add({
                        severity: 'error',
                        summary: '加载失败',
                        detail: response.message || '无法加载用户数据',
                        life: 3000
                    });
                }
            } catch (error) {
                this.$toast.add({
                    severity: 'error',
                    summary: '加载失败',
                    detail: '无法加载用户数据',
                    life: 3000
                });
                console.error('加载用户失败:', error);
            } finally {
                this.loading = false;
            }
        },
        resetSearch() {
            this.searchQuery = {
                code: null,
                questionBankIds: null,
                status: null,
                createTimeRange: null
            };
            this.selectedQuestionBank = null;
            this.loadUser();
        },

        onPage(event) {
            this.pageNum = event.page + 1;
            this.pageSize = event.rows;
            this.loadUser();
        },
        onSort(event) {
            let sortField = event.sortField;
            let sortOrder = event.sortOrder;
            if (sortField) {
                this.users.sort((a, b) => {
                    let result = 0;
                    if (a[sortField] < b[sortField]) {
                        result = -1;
                    } else if (a[sortField] > b[sortField]) {
                        result = 1;
                    }
                    return sortOrder === 1 ? result : -result;
                });
            }
        },

        performSearch() {
            this.pageNum = 1;
            this.loadUser();
        },

        confirmDeleteUser(user) {
            this.user = user;
            this.deleteUserDialog = true;
        },

        exportCSV() {
            this.$refs.dt.exportCSV();
        },
        updateUserStatus(value, data) {
            this.loading = true;
            const status = value ? 1 : 0;
            updateStatus(data.id, status).then(() => {
                this.$toast.add({
                    severity: 'info',
                    summary: '更新状态',
                    detail: `用户 ${data.id} 的状态已更新为 ${status == 1 ? '有效' : '无效'}`,
                    life: 3000
                });
                this.loading = false;
            });
        }
    },
    setup() {
        const toast = useToast();
        const router = useRouter();
        return { toast, router };
    }
};
</script>

<template>
    <div>
        <div class="card">
            <Toast />
            <Toolbar class="mb-6">
                <template #end>
                    <Button label="导出" icon="pi pi-upload" severity="secondary" @click="exportCSV($event)" />
                </template>
            </Toolbar>
            <Toolbar>
                <template #start>
                    <div class="flex flex-wrap items-center gap-2">
                        <FloatLabel variant="on">
                            <InputText v-model="searchQuery.id" id="searchById" />
                            <label for="searchById">Search By ID</label>
                        </FloatLabel>
                        <FloatLabel variant="on">
                            <InputText v-model="searchQuery.email" id="searchByEmail" />
                            <label for="searchByEmail">Search By Email</label>
                        </FloatLabel>
                        <FloatLabel variant="on">
                            <Select v-model="searchQuery.role" :options="roles" optionLabel="label" optionValue="value" id="chooseRole" :showClear="true" style="width: 150px" />
                            <label for="chooseRole">Choose Role</label>
                        </FloatLabel>
                        <FloatLabel variant="on">
                            <Select v-model="searchQuery.status" :options="statuses" optionLabel="label" optionValue="value" id="chooseStatus" :showClear="true" style="width: 150px" />
                            <label for="chooseStatus">Choose Status</label>
                        </FloatLabel>
                        <FloatLabel variant="on">
                            <DatePicker
                                showButtonBar
                                style="width: 300px"
                                v-model="searchQuery.createTimeRange"
                                selectionMode="range"
                                :showIcon="true"
                                id="selectCreateTimeRange"
                                dateFormat="yy-mm-dd"
                                hourFormat="24"
                                showTime
                                timeFormat="HH:mm:ss"
                                :manualInput="false"
                            />
                            <label for="selectCreateTimeRange">Select Create Time Range</label>
                        </FloatLabel>
                        <Button v-if="Object.values(searchQuery).some((value) => value !== null && value !== '')" label="重置" icon="pi pi-eraser" severity="info" @click="resetSearch" color="mr-2" />
                    </div>
                </template>
                <template #end>
                    <Button label="搜索" icon="pi pi-search" @click="performSearch" />
                </template>
            </Toolbar>
            <DataTable
                ref="dt"
                v-model:selection="selectedUser"
                :value="users"
                dataKey="id"
                :paginator="true"
                :rows="pageSize"
                lazy
                :totalRecords="totalRecords"
                scrollable
                :loading="loading"
                @page="onPage($event)"
                @sort="onSort($event)"
                :filters="filters"
                paginatorTemplate="FirstPageLink PrevPageLink PageLinks NextPageLink LastPageLink CurrentPageReport RowsPerPageDropdown"
                :rowsPerPageOptions="[5, 10, 20, 50]"
                currentPageReportTemplate="显示 {first} 到 {last} 共 {totalRecords} 条记录"
            >
                <template #header>
                    <h4 class="m-0">用户列表</h4>
                </template>

                <Column selectionMode="multiple" style="width: 3rem" :exportable="false"></Column>
                <Column field="id" frozen header="ID" sortable style="min-width: 5rem" bodyClass="text-center"></Column>
                <Column header="avatar" bodyClass="text-center">
                    <template #body="slotProps">
                        <img :src="slotProps.data.avatar" :alt="slotProps.data.avatar" class="rounded" style="width: 64px" />
                    </template>
                </Column>
                <Column field="email" frozen header="邮箱" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="username" frozen header="用户名" sortable style="min-width: 10rem" bodyClass="text-center"></Column>
                <Column field="nickName" header="昵称" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column field="status" header="角色" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <Tag :severity="slotProps.data.role === 1 ? 'info' : 'secondary'" :value="roles.find((s) => s.value === slotProps.data.role)?.label || '未知'" />
                    </template>
                </Column>
                <Column field="status" header="状态" sortable style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <ToggleButton
                            v-model="slotProps.data.status"
                            onLabel="有效"
                            offLabel="无效"
                            onIcon="pi pi-lock"
                            offIcon="pi pi-lock-open"
                            class="w-36"
                            aria-label="Do you confirm"
                            @update:modelValue="updateUserStatus($event, slotProps.data)"
                        />
                        <!--                        <Tag :severity=" 'info' : 'secondary'" :value="statuses.find((s) => s.value === slotProps.data.status)?.label || '未知'" />-->
                    </template>
                </Column>
                <Column field="createTime" header="创建时间" sortable style="min-width: 16rem" bodyClass="text-center"></Column>
                <Column frozen alignFrozen="right" header="操作" style="min-width: 10rem" bodyClass="text-center">
                    <template #body="slotProps">
                        <Button disabled icon="pi pi-trash" outlined rounded severity="danger" @click="confirmDeleteUser(slotProps.data)" />
                    </template>
                </Column>
            </DataTable>
        </div>
    </div>
</template>
